/** 全局仅加载一次 */

import { useToggle } from '@vueuse/core';
import { Result, Spin } from 'ant-design-vue';
import { type Component } from 'vue';
export interface ShortcutItem {
  label: string;
  component: Component<{ defaultValue?: Record<string, any>; open?: boolean }>;
  key: string;
  sort?: number;
  title: string;
  group?: string;
  defaultValue?: Record<string, any> | (() => Record<string, any>);
}
async function init() {
  const modules: Record<string, () => Promise<any>> = import.meta.glob('@/views/*/index.ts', {
    import: 'shortcutCreate',
  });
  const value: Record<string, ShortcutItem> = {};
  for (const fileKey in modules) {
    const shortcutCreate: any = await modules[fileKey]();
    const arr: any[] = [];
    /** 有可能一个页面上有多个新增操作 如 新增权限和新增权限组 */
    if (Array.isArray(shortcutCreate)) {
      arr.push(...shortcutCreate);
    } else if (shortcutCreate && typeof shortcutCreate === 'object') {
      arr.push(shortcutCreate);
    }
    arr
      /** 过滤没有导出组件的配置 @todo 后续需要严谨判断 */
      .filter(item => item.component)
      .forEach(({ key, component, title, label, ...rest }) => {
        value[key ?? fileKey] = {
          key: key ?? fileKey,
          label: label ?? `新增${title}`,
          title: title,
          ...rest,
          component: defineAsyncComponent({
            loader: component,
            delay: 200,
            timeout: 3000,
            loadingComponent: Spin,
            errorComponent: () => [h(Result, { status: '404', title: '组件加载失败' })],
          }),
        };
      });
  }
  return value;
}
const getMenus = init();

export function useShortcutCreateMenu() {
  const [loading, toggleLoading] = useToggle();
  const menusMap = shallowRef<Record<string, ShortcutItem>>({});
  const menus = computed(() =>
    Object.values(menusMap.value).sort((prev, next) => (prev.sort ?? 0) - (next.sort ?? 0)),
  );

  /** @todo 按照分组展示快捷菜单 */
  const groupedMenus = computed(() => {
    const obj: Record<
      string,
      { label: string; key: string; children: ShortcutItem[]; sort: number }
    > = {};
    menus.value.forEach(item => {
      const groupName = item.group ?? '其它';
      if (!(groupName in obj)) {
        obj[groupName] = {
          label: groupName,
          key: groupName,
          children: [item],
          sort: item.sort ?? 0,
        };
      } else {
        obj[groupName].children.push(item);
      }
    });
    return Object.values(obj).sort((prev, next) => (prev.sort ?? 0) - (next.sort ?? 0));
  });
  toggleLoading();
  getMenus.then(res => {
    menusMap.value = res;
    toggleLoading();
  });
  return {
    loading,
    menusMap,
    menus,
    groupedMenus,
  };
}
